/**
 * 统一日志管理工具
 * 替换项目中的 console.log 调用
 */

export enum LogLevel {
  DEBUG = 0,
  INFO = 1,
  WARN = 2,
  ERROR = 3,
}

class Logger {
  private level: LogLevel = LogLevel.INFO;
  private isDevelopment = process.env.NODE_ENV === 'development';

  setLevel(level: LogLevel): void {
    this.level = level;
  }

  private shouldLog(level: LogLevel): boolean {
    return level >= this.level;
  }

  private formatMessage(level: string, message: string, ...args: any[]): void {
    if (!this.isDevelopment) return;

    const timestamp = new Date().toISOString();
    const prefix = `[${timestamp}] [${level}]`;
    
    if (args.length > 0) {
      console.log(prefix, message, ...args);
    } else {
      console.log(prefix, message);
    }
  }

  debug(message: string, ...args: any[]): void {
    if (this.shouldLog(LogLevel.DEBUG)) {
      this.formatMessage('DEBUG', message, ...args);
    }
  }

  info(message: string, ...args: any[]): void {
    if (this.shouldLog(LogLevel.INFO)) {
      this.formatMessage('INFO', message, ...args);
    }
  }

  warn(message: string, ...args: any[]): void {
    if (this.shouldLog(LogLevel.WARN)) {
      this.formatMessage('WARN', message, ...args);
    }
  }

  error(message: string, error?: Error, ...args: any[]): void {
    if (this.shouldLog(LogLevel.ERROR)) {
      if (error) {
        this.formatMessage('ERROR', message, error.message, error.stack, ...args);
      } else {
        this.formatMessage('ERROR', message, ...args);
      }
    }
  }

  // 生产环境错误上报（可扩展）
  reportError(error: Error, context?: Record<string, any>): void {
    if (this.isDevelopment) {
      this.error('Reported Error:', error, context);
    } else {
      // 这里可以集成错误上报服务，如 Sentry
      console.error('Production Error:', error.message, context);
    }
  }
}

export const logger = new Logger();

// 开发环境下设置为 DEBUG 级别
if (process.env.NODE_ENV === 'development') {
  logger.setLevel(LogLevel.DEBUG);
}